﻿using LeaderCCSLaserUI.Data;
using LeaderCCSLaserUI.Data.Extensions;
using LeaderCCSLaserUI.Models;
using MvCamCtrl.NET;
using Newtonsoft.Json;
using Prism.Commands;
using Prism.Regions;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
using System.Windows.Forms;
using MessageBox = System.Windows.Forms.MessageBox;

namespace LeaderCCSLaserUI.ViewModels.Home
{
    public class WorkMapViewModel : NavigationViewModel
    {
        #region 变量
        Param systemParam;
        bool isCameraCalibDialogShow = false;
        private readonly IDialogService _dialogService;
        #endregion
        #region 属性
        private CompositeCollection compositeData = new CompositeCollection();
        public CompositeCollection CompositeData
        {
            get { return compositeData; }
            set { SetProperty(ref compositeData, value); }
        }
        private ObservableCollection<WeldPointDisp> weldPointDispList = new ObservableCollection<WeldPointDisp>();
        private ObservableCollection<WeldPathDisp> weldPathDispList = new ObservableCollection<WeldPathDisp>();
        private double drawWidth;
        public double DrawWidth
        {
            get { return drawWidth; }
            set { SetProperty(ref drawWidth, value); }
        }
        private double drawHeight;
        public double DrawHeight
        {
            get { return drawHeight; }
            set { SetProperty(ref drawHeight, value); }
        }
        #endregion
        #region 命令
        private DelegateCommand<object> pcsButtonCommand;

        public DelegateCommand<object> PcsButtonCommand =>
            pcsButtonCommand ?? (pcsButtonCommand = new DelegateCommand<object>(ExecutePcsButtonCommand));

        void ExecutePcsButtonCommand(object obj)
        {
            if (!isCameraCalibDialogShow)
            {
                isCameraCalibDialogShow = true;
                DialogParameters param = new DialogParameters();
                param.Add("PointId", int.Parse(obj.ToString()));
                _dialogService.Show("CameraVisionDialog", param, arg =>
                {
                    isCameraCalibDialogShow = false;
                });
            }
        }
        #endregion
        #region 导航
        public override void OnNavigatedFrom(NavigationContext navigationContext)
        {

        }

        public override void OnNavigatedTo(NavigationContext navigationContext)
        {
            LoadParam();
            DrawWidth = systemParam.BorderWidth;
            DrawHeight = systemParam.BorderHeight;
            UpdateDispMap();
        }
        #endregion
        #region 构造函数
        public WorkMapViewModel(IContainerProvider containerProvider) : base(containerProvider)
        {
            CompositeData.Add(new CollectionContainer() { Collection = weldPointDispList });
            CompositeData.Add(new CollectionContainer() { Collection = weldPathDispList });
            _dialogService = containerProvider.Resolve<IDialogService>();
            aggregator.ResgiterMessage(arg => {
                try
                {
                    if (arg.Message != null)
                    {
                        string[] strs = arg.Message.Split(';');
                        switch (strs[0])
                        {
                            case "ReloadParam":
                                LoadParam();
                                UpdateDispMap();
                                break;
                            case "UpdateDispMap":
                                UpdateDispMap();
                                break;
                            case "Reset":
                                {
                                    foreach (var item in weldPointDispList)
                                    {
                                        item.Select = false;
                                    }
                                }
                                break;
                            case "Select":
                                {
                                    if (int.TryParse(strs[1], out var id))
                                    {
                                        var vp = weldPointDispList.FirstOrDefault(p => p.Id == id);
                                        if (vp != null) { vp.Select = true; }
                                    }
                                }
                                break;
                            default:
                                break;
                        }
                    }
                    
                }
                catch { }
               
            }, "Run");
        }
        #endregion
        #region 功能函数
        void LoadParam()
        {
            try
            {
                //Json序列化，从文件读取
                string jsonString = File.ReadAllText(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "Param.json"));
                systemParam = JsonConvert.DeserializeObject<Param>(jsonString);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        void UpdateDispMap()
        {
            weldPointDispList.Clear();
            weldPathDispList.Clear();
            try
            {
                using var mdb = new MDbContext(systemParam.PartList[systemParam.PartIndex]);
                var points = mdb.XYZRPoints.Where(p => p.Hand == 0).OrderBy(p => p.PcsOrder);
                if (points.Any())
                {
                    int _index = 0; double x1 = 0, y1 = 0;
                    points.ToList().ForEach(p =>
                    {
                        if (_index > 0)
                        {
                            weldPathDispList.Add(new WeldPathDisp
                            {
                                Left = 0,
                                Bottom = 0,
                                X1 = x1,
                                Y1 = y1,
                                X2 = p.X - 20,
                                Y2 = DrawHeight - (p.Y - 60),
                                Stroke = "#191970"
                            });
                        }
                        x1 = p.X - 20;
                        y1 = DrawHeight - (p.Y - 60);
                        _index++;

                        weldPointDispList.Add(new WeldPointDisp
                        {
                            Id = p.Id,
                            Width = 40,
                            Height = 40,
                            Left = (p.X - 40),
                            Bottom = DrawHeight + (p.Y - 40) * -1,
                            Name = p.Name,
                            Select = false
                        });

                    });
                   
                }
                points = mdb.XYZRPoints.Where(p => p.Hand == 1).OrderBy(p => p.PcsOrder);
                if (points.Any())
                {
                    int _index = 0; double x1 = 0, y1 = 0;
                    points.ToList().ForEach(p =>
                    {
                        weldPointDispList.Add(new WeldPointDisp
                        {
                            Id = p.Id,
                            Width = 40,
                            Height = 40,
                            Left = (p.X - 40),
                            Bottom = DrawHeight + (p.Y - 40) * -1,
                            Name = p.Name,
                            Select = false
                        });

                        if (_index > 0)
                        {
                            weldPathDispList.Add(new WeldPathDisp
                            {
                                Left = 0,
                                Bottom = 0,
                                X1 = x1,
                                Y1 = y1,
                                X2 = p.X -20,
                                Y2 = DrawHeight - (p.Y - 60),
                                Stroke = "#8B0000"
                            });
                        }
                        x1 = p.X - 20;
                        y1 = DrawHeight - (p.Y - 60);
                        _index++;
                    });
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
        #endregion
    }
}
